import { Body, Controller, Del, Files, Get, Inject, Post, Query, UseGuard } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { ImagesService } from '../service/images.service';
import { UploadFileInfo, UploadMiddleware } from '@midwayjs/busboy';
import { promisify } from 'node:util';
import { pipeline } from 'node:stream';
import { createReadStream, createWriteStream, unlink } from 'node:fs';
import { join } from 'path';
import { basename } from 'path';
import { ImagesEntity } from '../entity/images.entity';
import { getAllImagesInfo, IdDTO } from '../dto/images';
import { AuthGuard } from '../guard/auth.guard';
import { Role } from '../decorator/role.decorator';


@Controller('images')
export class UserController {
  @Inject()
  ctx: Context;

  @Inject()
  imagesService: ImagesService;

  //上传文件
  @Post('/upload', { middleware: [UploadMiddleware] })
  async upload(@Files() files: Array<UploadFileInfo>) {
    const data = [];
    // 遍历上传的文件
    for (const file of files) {
      file.filename = Buffer.from(file.filename, 'latin1').toString('utf8');
      const tempFilePath = file.data; // 临时文件路径
      const fileName = basename(tempFilePath);
      const targetPath = join(__dirname, '../../public/images', fileName); // 目标路径
      // 使用 pipeline 将临时文件移动到目标路径
      await promisify(pipeline)(
        createReadStream(tempFilePath), // 从临时文件读取
        createWriteStream(targetPath),  // 写入目标路径
      );
      const url = join('/public/images', fileName);
      const result = await this.imagesService.addImages({
        name: file.filename,
        type: file.mimeType,
        url: url,
        user: this.ctx.user.id,
      } as ImagesEntity);
      if (result.identifiers.length > 0) {
        data.push({
          id: result.identifiers[0].id,
          name: file.filename,
          url: url,
        });
      } else {
        // 添加失败，删除文件
        await promisify(unlink)(targetPath);
      }
    }
    // 清理临时文件
    await this.ctx.cleanupRequestFiles();
    return data;
  }

  //根据token 获取自己的图片列表
  @Get('/my-images')
  async myImages(@Query() data: getAllImagesInfo) {
    return this.imagesService.getImages(data, this.ctx.user.id, { name: data?.name });
  }

  //获取所有的图片列表
  @UseGuard(AuthGuard)
  @Role(['root'])
  @Get('/all-images')
  async getAllImages(@Query() data: getAllImagesInfo) {
    return this.imagesService.getImages(data, undefined, { name: data?.name });
  }

  //删除图片
  @Del('/del')
  async delImages(@Body() data: IdDTO) {
    let userId = this.ctx.user.id;
    if (this.ctx.user.role == 'root') {
      userId = undefined;
    }
    const imgList = await this.imagesService.getImages({ skip: 0, take: 1 }, userId, { id: data.id });
    if (imgList.results.length == 0) {
      return { success: false, message: '删除失败没有该图片' };
    }
    const targetPath = join(__dirname, '../../', imgList.results[0].url); // 目标路径
    await promisify(unlink)(targetPath);
    const { affected } = await this.imagesService.delete(data.id);
    return affected == 1;
  }
}
